<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Annotation\ModuleAndAction;
use App\Controller\AbstractController;
use App\Exception\BusinessException;
use App\Helper\ApiHelper;
use App\Middleware\AdminMiddleware;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Redis;

/**
 * @AutoController()
 * @Middleware(AdminMiddleware::class)
 */
class ClearCacheController extends AbstractController
{
    /**
     * @ModuleAndAction(module="管理后台:系统设置:清理缓存", action="查看", icon="fa fa-trash")
     */
    public function index(): ResponseInterface
    {
        return $this->response->json(ApiHelper::genSuccessData());
    }

    /**
     * @ModuleAndAction(module="管理后台:系统设置:清理缓存", action="清理")
     */
    public function clear(): ResponseInterface
    {
        $pool = 'default';
        /* @var Redis $redis */
        $redis = ApplicationContext::getContainer()->get(RedisFactory::class)->get($pool);
        if (!$redis) {
            throw new BusinessException(0, '连接Redis-' . $pool . '失败 !');
        }
        $prefix = config('cache.default.prefix', 'c:');
        $count = 100;
        $iteratorA = null;
        $stopA = false;
        $patternA = $prefix . 'models_cache:' . $pool . ':*';
        $iteratorB = null;
        $stopB = false;
        $patternB = $prefix . 'menu_tree_data:*';
        while (!$stopA || !$stopB) {
            if (!$stopA) {
                $keys = $redis->scan($iteratorA, $patternA, $count);
                if ($keys === false) {
                    $stopA = true;
                } elseif ($keys) {
                    $redis->del($keys);
                }
            }
            if (!$stopB) {
                $keys = $redis->scan($iteratorB, $patternB, $count);
                if ($keys === false) {
                    $stopB = true;
                } elseif ($keys) {
                    $redis->del($keys);
                }
            }
        }
        return $this->response->json(ApiHelper::genSuccessData());
    }
}
